
package com.cspg.design.ui.map;

import android.app.AlertDialog;

import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.cspg.design.CSPGApplication;
import com.cspg.design.CheckPermissionsActivity;
import com.cspg.design.R;
import com.cspg.design.bean.UserInfo;
import com.cspg.design.bean.deviceBean.CrossDeviceBean;
import com.cspg.design.bean.deviceBean.PointDeviceBean;
import com.cspg.design.bean.deviceBean.PolylineDeviceBean;
import com.cspg.design.bean.projectBean.ProjectBean;
import com.cspg.design.bean.shemeBean.MyHighVoltageSchemeBean;
import com.cspg.design.bean.shemeBean.MyLowVoltageSchemeBean;
import com.cspg.design.dao.gen.CrossDeviceBeanDao;
import com.cspg.design.dao.gen.DaoSession;
import com.cspg.design.dao.gen.MyHighVoltageSchemeBeanDao;
import com.cspg.design.dao.gen.MyLowVoltageSchemeBeanDao;
import com.cspg.design.dao.gen.PointDeviceBeanDao;
import com.cspg.design.dao.gen.PolylineDeviceBeanDao;
import com.cspg.design.dao.gen.ProjectBeanDao;
import com.cspg.design.presenter.GTaskPresenter;
import com.cspg.design.presenter.SchemePresenter;
import com.cspg.design.ui.gtasks.GTasksActivity;
import com.cspg.design.ui.pointDevice.PointDeviceActivity;
import com.cspg.design.ui.pointDevice.PolylineDeviceActivity;
import com.cspg.design.ui.project.PoleAndWireActivity;
import com.cspg.design.ui.project.ProjectTotal;
import com.cspg.design.ui.workmap.WorkMapActivity;
import com.cspg.design.utils.NotificationUtils;
import com.cspg.design.utils.ShowSystemUIUtil;
import com.cspg.design.utils.StringSubstringUtil;
import com.cspg.design.utils.Utils;
import com.cspg.design.widget.AlertListDialog;
import com.cspg.design.widget.ToastUtils;

import org.greenrobot.greendao.rx.RxDao;
import org.greenrobot.greendao.rx.RxQuery;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.Inflater;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class DesignMapActivity extends CheckPermissionsActivity implements View.OnClickListener {

    private LocationClient mClient;
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private boolean isFirstLoc = true;
    private MyLocationListener myLocationListener;
    private LatLng preLatLng;

    private DrawerLayout mDrawerLayout;
    //设计模式，0手动 1自动
    private int design_preference = 0;
    //选择设备的资源类型
    private int device_type = 0;
    //设备名称
    private String device_name;
    //前基类型
    private int pre_device_type = 0;
    //方案名称
    private String schemeName;

    //点设备和线设备查询
    private RxDao<PointDeviceBean, String> pointDeviceBeanLongRxDao;
    private RxQuery<PointDeviceBean> pointDeviceBeanRxQuery;
    private RxDao<PolylineDeviceBean, String> polylineDeviceBeanLongRxDao;
    private RxQuery<PolylineDeviceBean> polylineDeviceBeanRxQuery;

    private DaoSession daoSession;
    private PointDeviceBean prePoint = null;
    private PointDeviceBean curPoint = null;

    private String projectId;

    private final Map<String, Overlay> deviceMap = new HashMap<>();
    private final Map<String, String> deviceNameMap = new HashMap<>();

    //禁止点击添加设备
    private boolean forbid = false;
    //设备型号
    private String poleModel;
    //导线型号
    private String wireModel;
    //变压器型号
    private String transformerModel;
    //项目信息
    private ProjectBean projectBean;

    private final String[] crossInfo = {
            "10kV线路、等级公路（10kV线路）",
            "导线跨越 低压电力线路、通信线路（10kV线路）",
            "经济作物、房屋（10kV线路）",
            "导线跨越 跨越河流 导线截面150以内 河宽50m以内（10kV线路）",
            "导线跨越 跨越河流 导线截面300以内 河宽150m以内（10kV线路）",
            "10kV线路、等级公路（380V、220V线路）",
            "导线跨越 低压电力线路、通信线路（380V、220V线路）",
            "经济作物、房屋（380V、220V线路）",
            "导线跨越 跨越河流 导线截面150以内 河宽50m以内（380V、220V线路）",
            "导线跨越 跨越河流 导线截面300以内 河宽150m以内（380V、220V线路）"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_design_map);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        ShowSystemUIUtil.hideSystemUI(this);
        daoSession = ((CSPGApplication) getApplication()).getDaoSession();
        pointDeviceBeanLongRxDao = daoSession.getPointDeviceBeanDao().rx();
        polylineDeviceBeanLongRxDao = daoSession.getPolylineDeviceBeanDao().rx();
//        pointDeviceBeanLongRxDao.deleteAll().subscribe();
//        polylineDeviceBeanLongRxDao.deleteAll().subscribe();
        schemeName = getIntent().getStringExtra("schemeName");

        mMapView = findViewById(R.id.mv_design_map);
        //隐藏缩放控件
//        mMapView.showZoomControls(false);
        //隐藏比例尺
        mMapView.showScaleControl(false);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        // 隐藏logo
        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
        }

        Button mBtnReturn = findViewById(R.id.bar_btn_return);
        mBtnReturn.setOnClickListener(this);

        Button mBtnSlideShow = findViewById(R.id.bar_show);
        mBtnSlideShow.setOnClickListener(this);
        if (UserInfo.getInstance().role.contains("设计")) {
            mBtnSlideShow.setVisibility(View.GONE);
            findViewById(R.id.bar_iv_show).setVisibility(View.INVISIBLE);
            forbid = true;
        }

        Button mBtnLocation = findViewById(R.id.bar_location);
        mBtnLocation.setOnClickListener(this);
        if (UserInfo.getInstance().role.contains("设计")) {
            mBtnLocation.setVisibility(View.GONE);
            findViewById(R.id.bar_iv_location).setVisibility(View.INVISIBLE);
        }

        Button mBtnExport = findViewById(R.id.bar_map_export);
        mBtnExport.setOnClickListener(this);

        Button mBtnPreferences = findViewById(R.id.bar_preferences);
        mBtnPreferences.setOnClickListener(this);
        if (UserInfo.getInstance().role.contains("设计")) {
            mBtnPreferences.setVisibility(View.GONE);
            findViewById(R.id.bar_iv_preferences).setVisibility(View.INVISIBLE);
        }

        Button mBtnCloseClick = findViewById(R.id.bar_close_click);
        mBtnCloseClick.setOnClickListener(this);
        if (UserInfo.getInstance().role.contains("设计")) {
            mBtnCloseClick.setVisibility(View.GONE);
            findViewById(R.id.bar_iv_close_click).setVisibility(View.INVISIBLE);
        }

        ImageButton mBtnTower = findViewById(R.id.slider_tower);
        mBtnTower.setOnClickListener(this);

        ImageButton mBtnSettingFire = findViewById(R.id.slider_setting_fire);
        mBtnSettingFire.setOnClickListener(this);

        ImageButton mBtnTransformer = findViewById(R.id.slider_transformer);
        mBtnTransformer.setOnClickListener(this);

        ImageButton mBtnEndPoint = findViewById(R.id.slider_end_point);
        mBtnEndPoint.setOnClickListener(this);

        ImageButton mBtnDoor = findViewById(R.id.slider_door);
        mBtnDoor.setOnClickListener(this);

        ImageButton mBtnCross = findViewById(R.id.slider_cross);
        mBtnCross.setOnClickListener(this);

        mDrawerLayout = findViewById(R.id.map_drawer_layout);

        initLocation();
        initNotification();
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (forbid) {
                    Toast.makeText(DesignMapActivity.this, "点击无效", Toast.LENGTH_SHORT).show();
                    return;
                }
                Log.e("LatLng", latLng.latitude + "/////" + latLng.longitude);
                if (design_preference == 1) {
                    Toast.makeText(DesignMapActivity.this, "当前为定位模式", Toast.LENGTH_SHORT).show();
                    return;
                }
                addDevice(latLng);
            }

            @Override
            public void onMapPoiClick(MapPoi mapPoi) {
                if (forbid) {
                    return;
                }
                LatLng latLng = mapPoi.getPosition();
                if (design_preference == 1) {
                    return;
                }
                addDevice(latLng);
            }
        });
//        mBaiduMap.setOnPolylineClickListener(new BaiduMap.OnPolylineClickListener() {
//            @Override
//            public boolean onPolylineClick(Polyline polyline) {
//                if (getDeviceType(device_type) == 6)
//                {
//                    return  false;
//                }
//                if (polyline != null) {
//                    polyline.setColor(R.color.colorPrimaryDark);
//                    Bundle bundle = polyline.getExtraInfo();
//                    String uuid = bundle.getString("uuid");
//                    Log.e(DesignMapActivity.class.getName(), "线段的UUID：" + uuid);
//                    new AlertDialog.Builder(DesignMapActivity.this)
//                            .setCancelable(true)
//                            .setItems(new String[]{"查看导线信息"}, (dialog, which) -> {
//                                Intent intent = new Intent(DesignMapActivity.this, PolylineDeviceActivity.class);
//                                intent.putExtra("uuid", uuid);
//                                startActivity(intent);
//                            })
//                            .setOnCancelListener(new DialogInterface.OnCancelListener() {
//                                @Override
//                                public void onCancel(DialogInterface dialog) {
//                                    polyline.setColor(R.color.RED);
//                                }
//                            })
//                            .create().show();
//                    return true;
//                }
//                return false;
//            }
//        });
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker != null) {
                    AlertDialog alertListDialog = makerDialog(marker);
                    if (alertListDialog != null) {
                        alertListDialog.show();
                    }
                }
                return false;
            }
        });
//        mBaiduMap.setOnMarkerDragListener(new BaiduMap.OnMarkerDragListener() {
//            @Override
//            public void onMarkerDrag(Marker marker) {
//
//            }
//
//            @Override
//            public void onMarkerDragEnd(Marker marker) {
//                Log.e("end", marker.getTitle());
//                marker.getPosition();
//            }
//
//            @Override
//            public void onMarkerDragStart(Marker marker) {
//                Log.e("start", marker.getTitle());
//            }
//        });
        mBaiduMap.setOnMapLoadedCallback(() -> {
            Log.e(DesignMapActivity.class.getName(), "地图加载完毕");
            initData();
        });
    }

    /**
     * 初始化定位参数
     */
    private void initLocation() {

        // 创建定位客户端
        mClient = new LocationClient(this);
        myLocationListener = new MyLocationListener();
        // 注册定位监听
        mClient.registerLocationListener(myLocationListener);
        LocationClientOption mOption = new LocationClientOption();
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        mOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        // 可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
        mOption.setScanSpan(1000);
        // 可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
        mOption.setCoorType("bd09ll");
        // 可选，默认false，设置是否开启Gps定位
        mOption.setOpenGps(true);
        // 设置定位参数
        mClient.setLocOption(mOption);
        mClient.start();
    }

    /**
     * 初始化前台服务
     */
    private void initNotification() {
        //设置后台定位
        //android8.0及以上使用NotificationUtils
        Notification mNotification;
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationUtils notificationUtils = new NotificationUtils(this);
            Notification.Builder builder = notificationUtils.getAndroidChannelNotification
                    ("适配android 8限制后台定位功能", "正在后台定位");
            mNotification = builder.build();
        } else {
            //获取一个Notification构造器
            Notification.Builder builder = new Notification.Builder(DesignMapActivity.this);
            Intent nfIntent = new Intent(DesignMapActivity.this, WorkMapActivity.class);

            builder.setContentIntent(PendingIntent.
                    getActivity(DesignMapActivity.this, 0, nfIntent, 0)) // 设置PendingIntent
                    .setContentTitle("适配android 8限制后台定位功能") // 设置下拉列表里的标题
                    .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                    .setContentText("正在后台定位") // 设置上下文内容
                    .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

            mNotification = builder.build(); // 获取构建好的Notification
        }
        mNotification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bar_btn_return:
                finish();
                break;
            case R.id.bar_show:
                if (mDrawerLayout.isDrawerVisible(GravityCompat.START)) {
                    mDrawerLayout.closeDrawer(GravityCompat.START);
                } else {
                    mDrawerLayout.openDrawer(GravityCompat.START);
                }
                break;
            case R.id.bar_location:
                addDeviceByLocation();
                break;
            case R.id.bar_map_export:
                Intent intent = new Intent(this, PoleAndWireActivity.class);
                intent.putExtra("projectId", projectId);
                startActivity(intent);
                break;
            case R.id.bar_preferences:
                final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                alertDialog.setTitle("设计模式").setItems(new String[]{"手动点击", "自动定位"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        design_preference = which;
                    }
                }).create();
                alertDialog.show();
                break;
            case R.id.bar_close_click:
                View parentV = (View) v.getParent();
                ImageView imageView = parentV.findViewById(R.id.bar_iv_close_click);
                if (v.getTag().equals("0")) {
                    forbid = true;
                    v.setTag("1");
                    imageView.setImageResource(android.R.drawable.star_big_on);
                } else {
                    forbid = false;
                    v.setTag("0");
                    imageView.setImageResource(android.R.drawable.star_big_off);
                }

                break;
            case R.id.slider_tower:
                device_type = R.drawable.ic_tower;
                mDrawerLayout.closeDrawer(GravityCompat.START);
                this.showDeviceModelDialog(1);
                break;
            case R.id.slider_setting_fire:
                device_type = R.drawable.ic_setting_fire;
                mDrawerLayout.closeDrawer(GravityCompat.START);
                this.showDeviceModelDialog(2);
                break;
            case R.id.slider_transformer:
                device_type = R.drawable.ic_trasform;
                mDrawerLayout.closeDrawer(GravityCompat.START);
                this.showDeviceModelDialog(3);
                break;
            case R.id.slider_end_point:
                device_type = R.drawable.ic_end_point;
                mDrawerLayout.closeDrawer(GravityCompat.START);
                this.showDeviceModelDialog(4);
                break;
            case R.id.slider_door:
                device_type = R.drawable.ic_door;
                mDrawerLayout.closeDrawer(GravityCompat.START);
                this.showDeviceModelDialog(5);
                break;
            case R.id.slider_cross:
                device_type = R.drawable.ic_cross;
                mDrawerLayout.closeDrawer(GravityCompat.START);
                this.showDeviceModelDialog(6);
                break;
        }
    }

    /**
     * 定位信息回调
     */
    class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation == null || mMapView == null) {
                return;
            }
//            bdLocation.setLatitude(26.56819);
//            bdLocation.setLongitude(106.7145);
            MyLocationData locData = new MyLocationData.Builder().accuracy(bdLocation.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(bdLocation.getDirection()).latitude(bdLocation.getLatitude())
                    .longitude(bdLocation.getLongitude()).build();
            // 设置定位数据
            mBaiduMap.setMyLocationData(locData);
            //地图SDK处理
            if (isFirstLoc && !UserInfo.getInstance().role.contains("设计")) {
                isFirstLoc = false;
                LatLng ll = new LatLng(bdLocation.getLatitude(),
                        bdLocation.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
            StringBuffer sb = new StringBuffer(256);
            sb.append("纬度: ");
            sb.append(bdLocation.getLatitude() + " , ");
            sb.append("经度: ");
            sb.append(bdLocation.getLongitude() + "\n");

        }
    }

    //设备名称对话框
    private AlertDialog.Builder getAlertDialog(final LatLng latLng) {
        AlertDialog.Builder alertDialot = new AlertDialog.Builder(this);
        // 创建一个view，并且将布局加入view中
        View view = LayoutInflater.from(this).inflate(
                R.layout.dialog_device_name, null, false);
        final EditText editText = view.findViewById(R.id.input_device_name);
        // 将view添加到builder中
        alertDialot.setView(view);
        alertDialot.setTitle("设备名称");
        alertDialot.setCancelable(true);
        alertDialot.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                device_name = editText.getText().toString();
                if (device_name.trim().isEmpty()) {
                    Toast.makeText(DesignMapActivity.this, "请输入设备名称", Toast.LENGTH_SHORT).show();
                } else {
                    insertDevice(latLng);
                    dialog.dismiss();
                }
            }
        });
        alertDialot.create();
        return alertDialot;
    }

    //添加线设备
    private void addPolyline(LatLng latLng, String uuid) {
        if (preLatLng == null) {
            preLatLng = latLng;
        } else {
            Bundle bundle = new Bundle();
            bundle.putString("uuid", uuid);
            List<LatLng> points = new ArrayList<>();
            points.add(preLatLng);
            points.add(latLng);
            preLatLng = latLng;
            OverlayOptions mOverLayerOptions = new PolylineOptions().width(5).color(Color.RED).extraInfo(bundle).points(points);
            Overlay overlay = mBaiduMap.addOverlay(mOverLayerOptions);
            this.deviceMap.put(uuid, overlay);
        }
    }

    //添加点设备
    private void addPoint(LatLng latLng, String uuid) {
        View marker_temp = null;
        if (getDeviceType(device_type ) == 6){
            marker_temp = LayoutInflater.from(getApplicationContext()).inflate(R.layout.marker_text_up_img_down_cross, null);
        }
        else {
            marker_temp = LayoutInflater.from(getApplicationContext()).inflate(R.layout.marker_text_up_img_down, null);
        }
        TextView marker_tv_temp = marker_temp.findViewById(R.id.baidumap_custom_text);
        ImageView marker_img_temp = marker_temp.findViewById(R.id.baidumap_custom_img);
        if (getDeviceType(device_type) == 6) {
            marker_tv_temp.setText(" ");
        } else {
            marker_tv_temp.setText(device_name);
        }
        if (device_type == 0) {
            marker_img_temp.setImageResource(R.drawable.ic_tower);
        } else {
            marker_img_temp.setImageResource(device_type);
        }
        Bundle bundle = new Bundle();
        bundle.putString("uuid", uuid);
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromView(marker_temp);
        OverlayOptions options = new MarkerOptions()
                .position(latLng)
                .icon(bitmapDescriptor)
                .title(uuid)
                .draggable(true)
                .yOffset(45)
                .extraInfo(bundle);
        Overlay overlay = mBaiduMap.addOverlay(options);
        pre_device_type = device_type;
        this.deviceMap.put(uuid, overlay);
        if (getDeviceType(device_type) == 6) {
            this.deviceNameMap.put(uuid, " ");
        } else {
            this.deviceNameMap.put(uuid, device_name);
        }
    }

    //定位模式添加设备
    private void addDeviceByLocation() {
        //设计模式为定位模式
        if (design_preference == 0) {
            Toast.makeText(this, "当前为手动模式，请设置为定位模式", Toast.LENGTH_LONG).show();
            return;
        }

        BDLocation bdLocation = mClient.getLastKnownLocation();
        LatLng latLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
        addDevice(latLng);
    }

    private void addDevice(LatLng latLng) {
        if (device_type == 0) {
            Toast.makeText(DesignMapActivity.this, "请选择设备类型", Toast.LENGTH_SHORT).show();
            mDrawerLayout.openDrawer(GravityCompat.START);
            return;
        }
        if (getDeviceType(device_type) == 1 && (poleModel == null || poleModel.isEmpty())) {
            Toast.makeText(DesignMapActivity.this, "方案中无杆塔型号，请修改项目方案", Toast.LENGTH_SHORT).show();
            return;
        } else if (wireModel == null || wireModel.isEmpty()) {
            Toast.makeText(DesignMapActivity.this, "方案中无导线型号，请修改项目方案", Toast.LENGTH_SHORT).show();
            return;
        }
        if (getDeviceType(device_type) == 3 && (transformerModel == null || transformerModel.isEmpty())) {
            Toast.makeText(DesignMapActivity.this, "方案中无变压器类型，请修改项目方案", Toast.LENGTH_SHORT).show();
            return;
        }
        if (getDeviceType(device_type) != 6) {
            if (device_name == null || device_name.isEmpty()) {
                getAlertDialog(latLng).show();
                return;
            }
            if (pre_device_type == device_type) {
                String str = StringSubstringUtil.subStringNumPP(device_name);
                if (str.equals(device_name)) {
                    Toast.makeText(DesignMapActivity.this, "设备名称不能自动识别", Toast.LENGTH_SHORT).show();
                    getAlertDialog(latLng).show();
                    return;
                } else {
                    device_name = str;
                }
            } else {
                getAlertDialog(latLng).show();
                return;
            }
        }
        insertDevice(latLng);
    }

    /**
     * 设置状态栏的显示监听器，当状态栏显示时，将其隐藏！
     */
    private void setOnSystemUiListener() {
        final View decor = getWindow().getDecorView();
        decor.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            public void onSystemUiVisibilityChange(int visibility) {

                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        //decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
                        try {
                            ShowSystemUIUtil.hideSystemUI(DesignMapActivity.this);
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                    }
                }, 500);
            }
        });
    }

    /**
     * 数据加载
     */
    private void initData() {
        projectId = getIntent().getStringExtra("projectId");
        if (projectId == null) {
            Toast.makeText(this, "无法获取到项目编号", Toast.LENGTH_SHORT).show();
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity(new Intent(DesignMapActivity.this, GTasksActivity.class));
                }
            }, 1000);
        } else {
            projectBean = daoSession.getProjectBeanDao().queryBuilder().where(ProjectBeanDao.Properties.ProjectId.eq(projectId)).unique();
            pointDeviceBeanRxQuery = daoSession.getPointDeviceBeanDao().queryBuilder().where(PointDeviceBeanDao.Properties.ProjectId.eq(projectId)).rx();
            pointDeviceBeanRxQuery.list().subscribe(this::initPoint);
            polylineDeviceBeanRxQuery = daoSession.getPolylineDeviceBeanDao().queryBuilder().where(PolylineDeviceBeanDao.Properties.ProjectId.eq(projectId)).rx();
            polylineDeviceBeanRxQuery.list().subscribe(this::initPolyline);
        }
    }

    //初始化点
    private void initPoint(List<PointDeviceBean> pointDeviceBeans) {
        for (int i = 0; i < pointDeviceBeans.size(); i++) {
            PointDeviceBean pointDeviceBean = pointDeviceBeans.get(i);
            if (pointDeviceBean.getPointType() != 6) {
                this.device_name = pointDeviceBean.getPointName();
                LatLng latLng = new LatLng(pointDeviceBean.getLatitude(), pointDeviceBean.getLongitude());
                this.device_type = getResourceId(pointDeviceBean.getPointType());
                addPoint(latLng, pointDeviceBean.getPointUuid());
                if (i == 0) {
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(latLng).zoom(22.0f);
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                    isFirstLoc = false;
                }
                if (pointDeviceBeans.size() > 0) {
                    this.prePoint = pointDeviceBeans.get(pointDeviceBeans.size() - 1);
                    if (prePoint.getPointType() == 1) {
                        this.poleModel = prePoint.getPointModel();
                    } else if (prePoint.getPointType() == 3) {
                        this.transformerModel = prePoint.getPointModel();
                    }
                    initPolylineModel();
                }
            } else {
                LatLng latLng = new LatLng(pointDeviceBean.getLatitude(), pointDeviceBean.getLongitude());
                this.device_type = getResourceId(pointDeviceBean.getPointType());
                addPoint(latLng, pointDeviceBean.getPointUuid());
                if (i == 0) {
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(latLng).zoom(22.0f);
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                    isFirstLoc = false;
                }
            }
        }

    }

    //初始化线
    private void initPolyline(List<PolylineDeviceBean> polylineDeviceBeans) {
        for (int i = 0; i < polylineDeviceBeans.size(); i++) {
            PolylineDeviceBean polylineDeviceBean = polylineDeviceBeans.get(i);
            preLatLng = new LatLng(polylineDeviceBean.getStartLatitude(), polylineDeviceBean.getStartLongitude());
            addPolyline(new LatLng(polylineDeviceBean.getEndLatitude(), polylineDeviceBean.getEndLongitude()), polylineDeviceBean.getPolylineUuid());
        }
        if (polylineDeviceBeans.size() > 0) {
            PolylineDeviceBean lastPolylineDeviceBean = polylineDeviceBeans.get(polylineDeviceBeans.size() - 1);
            preLatLng = new LatLng(lastPolylineDeviceBean.getEndLatitude(), lastPolylineDeviceBean.getEndLongitude());
            wireModel = polylineDeviceBeans.get(polylineDeviceBeans.size() - 1).getPolylineModel();
        }

    }

    //初始化线类型
    private void initPolylineModel() {
        ProjectBean projectBean = daoSession.getProjectBeanDao().queryBuilder().where(ProjectBeanDao.Properties.ProjectId.eq(projectId)).unique();
        switch (projectBean.getSchemaType()) {
            case "low":
                List<MyLowVoltageSchemeBean> myLowVoltageSchemeBeans = daoSession.getMyLowVoltageSchemeBeanDao().queryBuilder()
                        .where(MyLowVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                MyLowVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName()))
                        .list();
                if (myLowVoltageSchemeBeans == null || myLowVoltageSchemeBeans.size() ==0)  {
                    return;
                }
                else {
                    MyLowVoltageSchemeBean myLowVoltageSchemeBean = myLowVoltageSchemeBeans.get(0);
                    String wire380 = myLowVoltageSchemeBean.getWireModel380V();
                    String wire220 = myLowVoltageSchemeBean.getWireModel220V();
                    if (wire220 != null && !wire220.isEmpty()) {
                        wireModel = wire220;
                    } else {
                        wireModel = wire380;
                    }
                }
                break;
            case "high":
                MyHighVoltageSchemeBean myHighVoltageSchemeBean = daoSession.getMyHighVoltageSchemeBeanDao().queryBuilder()
                        .where(MyHighVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                MyHighVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName()))
                        .unique();
                if (myHighVoltageSchemeBean == null) {
                    return;
                }
                String model = myHighVoltageSchemeBean.getWireModel();
                wireModel = model;
                break;
        }
    }

    //通过资源id得到设备类型
    private int getDeviceType(int id) {
        //设备类型 1：杆塔 2： 搭火点  3： 变压器 4 ：用户点 5 ：门铁
        int devType = 0;
        switch (id) {
            case R.drawable.ic_tower:
                devType = 1;
                break;
            case R.drawable.ic_setting_fire:
                devType = 2;
                break;
            case R.drawable.ic_trasform:
                devType = 3;
                break;
            case R.drawable.ic_end_point:
                devType = 4;
                break;
            case R.drawable.ic_door:
                devType = 5;
                break;
            case R.drawable.ic_cross:
                devType = 6;
                break;
        }
        return devType;
    }

    //通过设备类型获取设备资源id
    private int getResourceId(int type) {
        //设备类型 1：杆塔 2： 搭火点  3： 变压器 4 ：用户点 5 ：门铁 6: 跨越
        int id = 0;
        switch (type) {
            case 1:
                id = R.drawable.ic_tower;
                break;
            case 2:
                id = R.drawable.ic_setting_fire;
                break;
            case 3:
                id = R.drawable.ic_trasform;
                break;
            case 4:
                id = R.drawable.ic_end_point;
                break;
            case 5:
                id = R.drawable.ic_door;
                break;
            case 6:
                id = R.drawable.ic_cross;
                break;
        }
        return id;
    }

    //插入点
    private void insertDevice(LatLng latLng) {
        if (getDeviceType(device_type) != 6) {
            PointDeviceBean pointDeviceBean = new PointDeviceBean();
            pointDeviceBean.setPointName(this.device_name);
            pointDeviceBean.setPointUuid(Utils.uuid());
            pointDeviceBean.setPointType(getDeviceType(device_type));
            if (getDeviceType(device_type) == 1) {
                pointDeviceBean.setPointModel(poleModel);
            } else if (getDeviceType(device_type) == 3) {
                pointDeviceBean.setPointModel(transformerModel);
            } else {
                pointDeviceBean.setPointModel(null);
            }
            if (preLatLng != null) {
                Double distance = DistanceUtil.getDistance(preLatLng, latLng);
                distance = new BigDecimal(distance).setScale(2, RoundingMode.UP).doubleValue();
                pointDeviceBean.setDistance(distance);
            } else {
                pointDeviceBean.setDistance(0D);
            }
            pointDeviceBean.setLatitude(latLng.latitude);
            pointDeviceBean.setLongitude(latLng.longitude);
            pointDeviceBean.setPointStatue(1);
            if (prePoint != null) {
                pointDeviceBean.setPrePointUUID(prePoint.getPointUuid());
            } else {
                pointDeviceBean.setPrePointUUID("");
            }

            pointDeviceBean.setSchemaName(schemeName);
            pointDeviceBean.setProjectId(projectId);
            pointDeviceBean.setPointId(daoSession.getPointDeviceBeanDao().count() + 1);
            curPoint = pointDeviceBean;
            pointDeviceBeanLongRxDao.insert(pointDeviceBean).subscribe(new Action1<PointDeviceBean>() {
                @Override
                public void call(PointDeviceBean pointDeviceBean) {
                    addPoint(latLng, pointDeviceBean.getPointUuid());
                    insertPolyline(latLng);
                    prePoint = pointDeviceBean;
                }
            });
        } else {
            PointDeviceBean pointDeviceBean = new PointDeviceBean();
            pointDeviceBean.setPointName("  ");
            pointDeviceBean.setPointUuid(Utils.uuid());
            pointDeviceBean.setPointType(getDeviceType(device_type));
            pointDeviceBean.setPointModel(null);
            pointDeviceBean.setDistance(0D);
            pointDeviceBean.setLatitude(latLng.latitude);
            pointDeviceBean.setLongitude(latLng.longitude);
            pointDeviceBean.setPointStatue(1);
            pointDeviceBean.setPrePointUUID("");
            pointDeviceBean.setSchemaName(schemeName);
            pointDeviceBean.setProjectId(projectId);
            pointDeviceBean.setPointId(daoSession.getPointDeviceBeanDao().count() + 1);
            pointDeviceBeanLongRxDao.insert(pointDeviceBean).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<PointDeviceBean>() {
                @Override
                public void call(PointDeviceBean pointDeviceBean) {
                    addPoint(latLng, pointDeviceBean.getPointUuid());
                    showCrossDialog(pointDeviceBean).show();
                }
            });
        }
    }

    //插入线
    private void insertPolyline(LatLng latLng) {
        if (prePoint == null) {
            return;
        }
        PolylineDeviceBean polylineDeviceBean = new PolylineDeviceBean();
        polylineDeviceBean.setStartLatitude(prePoint.getLatitude());
        polylineDeviceBean.setStartLongitude(prePoint.getLongitude());
        polylineDeviceBean.setEndLatitude(latLng.latitude);
        polylineDeviceBean.setEndLongitude(latLng.longitude);
        polylineDeviceBean.setCircuitsNum("");
        polylineDeviceBean.setMargin("");
        polylineDeviceBean.setPolylineModel(wireModel);
        polylineDeviceBean.setStartPointName(prePoint.getPointName());
        polylineDeviceBean.setEndPointName(curPoint.getPointName());
        polylineDeviceBean.setPolylineUuid(UUID.randomUUID().toString());
        polylineDeviceBean.setProjectId(projectId);
        polylineDeviceBean.setStartPointUUID(prePoint.getPointUuid());
        polylineDeviceBean.setEndPointUUID(curPoint.getPointUuid());
        preLatLng = new LatLng(prePoint.getLatitude(), prePoint.getLongitude());
        polylineDeviceBeanLongRxDao.insert(polylineDeviceBean).subscribe(new Action1<PolylineDeviceBean>() {
            @Override
            public void call(PolylineDeviceBean polylineDeviceBean) {
                addPolyline(latLng, polylineDeviceBean.getPolylineUuid());
            }
        });

    }

    //删除点
    private void deletePoint(Overlay overlay) {
        if (overlay == null) {
            return;
        }
        Bundle bundle = overlay.getExtraInfo();
        String uuid = bundle.getString("uuid");
        if (uuid == null) {
            return;
        }
        PointDeviceBean pointDeviceBean = daoSession.getPointDeviceBeanDao().queryBuilder().where(PointDeviceBeanDao.Properties.PointUuid.eq(uuid)).unique();
        Log.e("bean", pointDeviceBean.getPointName());
        if (pointDeviceBean != null) {
            List<PointDeviceBean> nextPoints = daoSession.getPointDeviceBeanDao()
                    .queryBuilder()
                    .where(PointDeviceBeanDao.Properties.PrePointUUID.eq(pointDeviceBean.getPointUuid()))
                    .list();
            if (pointDeviceBean.getPrePointUUID().isEmpty()) //起始点
            {
                if (nextPoints != null && nextPoints.size() > 1) {
                    Toast.makeText(this, "分线情况无法删除", Toast.LENGTH_LONG).show();
                } else if (nextPoints != null) {
                    overlay.remove();
                    this.deletePointBean(pointDeviceBean);
                    if (nextPoints.size() == 0) //孤立点
                    {
                        this.prePoint = null;
                        this.preLatLng = null;
                        this.device_name = null;
                        this.pre_device_type = 0;
                        this.device_type = 0;
                        this.deviceNameMap.clear();
                        this.deviceMap.clear();
                        return;
                    }

                    PointDeviceBean nextPointDeviceBean = nextPoints.get(0);
                    if (nextPointDeviceBean != null) {
                        deletePolyline(pointDeviceBean.getPointUuid(), nextPointDeviceBean.getPointUuid());
                        nextPointDeviceBean.setPrePointUUID(pointDeviceBean.getPrePointUUID());
                        pointDeviceBeanLongRxDao.update(nextPointDeviceBean).subscribe();
                    }
                }
            } else {
                if (nextPoints != null && nextPoints.size() > 1) {
                    Toast.makeText(this, "分线情况无法删除", Toast.LENGTH_LONG).show();
                } else {

                    List<PointDeviceBean> prePoints = daoSession.getPointDeviceBeanDao().queryBuilder()
                            .where(PointDeviceBeanDao.Properties.PointUuid.eq(pointDeviceBean.getPrePointUUID()))
                            .list();

                    if (prePoints != null && prePoints.size() > 1) {
                        Toast.makeText(this, "分线情况无法删除", Toast.LENGTH_LONG).show();
                    } else {

                        if (nextPoints != null
                                && nextPoints.size() == 0
                                && prePoints.size() > 0
                                && prePoints != null) //终点
                        {
                            PointDeviceBean prePointDeviceBean = prePoints.get(0);
                            overlay.remove();
                            this.deletePointBean(pointDeviceBean);
                            this.prePoint = prePointDeviceBean;
                            this.preLatLng = new LatLng(prePointDeviceBean.getLatitude(), prePointDeviceBean.getLongitude());
                            deletePolyline(prePointDeviceBean.getPointUuid(), pointDeviceBean.getPointUuid());
                        } else if (nextPoints != null
                                && nextPoints.size() > 0
                                && prePoints.size() > 0
                                && prePoints != null)//中间点
                        {
                            overlay.remove();
                            this.deletePointBean(pointDeviceBean);
                            PointDeviceBean nextPointDeviceBean = nextPoints.get(0);
                            PointDeviceBean prePointDeviceBean = prePoints.get(0);
                            nextPointDeviceBean.setPrePointUUID(prePointDeviceBean.getPointUuid());
                            nextPointDeviceBean.setDistance(DistanceUtil
                                    .getDistance(
                                            new LatLng(prePointDeviceBean.getLatitude(), prePointDeviceBean.getLongitude()),
                                            new LatLng(nextPointDeviceBean.getLatitude(), nextPointDeviceBean.getLongitude())));
                            pointDeviceBeanLongRxDao.update(nextPointDeviceBean).subscribe(); //更新点的上一级
                            updatePolyline(prePointDeviceBean, pointDeviceBean, nextPointDeviceBean);
                        }
                    }

                }
            }
        }
    }

    //删除线路
    private void deletePolyline(String startPointUUID, String endPointUUID) {
        RxQuery<PolylineDeviceBean> query = polylineDeviceBeanLongRxDao.getDao()
                .queryBuilder()
                .where(PolylineDeviceBeanDao.Properties.StartPointUUID.eq(startPointUUID)
                        , PolylineDeviceBeanDao.Properties.EndPointUUID.eq(endPointUUID))
                .rx();
        query.unique().subscribe(polylineDeviceBean -> {
            if (polylineDeviceBean != null) {
                String uuid = polylineDeviceBean.getPolylineUuid();
                if (!uuid.isEmpty()) {
                    Overlay overlay = deviceMap.get(uuid);
                    overlay.remove();
                    polylineDeviceBeanLongRxDao.delete(polylineDeviceBean).subscribe();
                }
            }
        });

    }

    //只能处理连续点，无分叉
    private void updatePolyline(PointDeviceBean startPointDevice, PointDeviceBean middlePointDevice, PointDeviceBean endPointDevice) {

        List<PolylineDeviceBean> polylineDeviceBeans = daoSession.getPolylineDeviceBeanDao().queryBuilder()
                .whereOr(PolylineDeviceBeanDao.Properties.StartPointUUID.eq(middlePointDevice.getPointUuid()),
                        PolylineDeviceBeanDao.Properties.EndPointUUID.eq(middlePointDevice.getPointUuid()))
                .list();
        if (polylineDeviceBeans.size() > 0) {
            for (int i = 0; i < polylineDeviceBeans.size(); i++) {
                PolylineDeviceBean polylineDeviceBean = polylineDeviceBeans.get(i);
                if (polylineDeviceBean == null) {
                    continue;
                }
                String uuid = polylineDeviceBean.getPolylineUuid();
                if (!uuid.isEmpty()) {
                    Overlay overlay = deviceMap.get(uuid);
                    if (overlay != null) {
                        overlay.remove();
                    }
                    daoSession.getPolylineDeviceBeanDao().delete(polylineDeviceBean);
                }
            }
            PolylineDeviceBean polylineDeviceBean = polylineDeviceBeans.get(0);
            String uuid = polylineDeviceBean.getPolylineUuid();
            Bundle bundle = new Bundle();
            bundle.putString("uuid", uuid);
            List<LatLng> points = new ArrayList<>();
            points.add(new LatLng(startPointDevice.getLatitude(), startPointDevice.getLongitude()));
            points.add(new LatLng(endPointDevice.getLatitude(), endPointDevice.getLongitude()));
            OverlayOptions mOverLayerOptions = new PolylineOptions().width(5).color(Color.RED).extraInfo(bundle).points(points);
            Overlay newOverlay = mBaiduMap.addOverlay(mOverLayerOptions);
            this.deviceMap.put(uuid, newOverlay);
            polylineDeviceBean.setStartPointUUID(startPointDevice.getPointUuid());
            polylineDeviceBean.setEndPointUUID(endPointDevice.getPointUuid());
            polylineDeviceBean.setStartLatitude(startPointDevice.getLatitude());
            polylineDeviceBean.setStartLongitude(startPointDevice.getLongitude());
            polylineDeviceBean.setEndLatitude(endPointDevice.getLatitude());
            polylineDeviceBean.setEndLongitude(endPointDevice.getLongitude());
            polylineDeviceBeanLongRxDao.insert(polylineDeviceBean).subscribe();

        }
    }

    //对点设备进行操作
    private AlertDialog makerDialog(final Marker marker) {
        String uuid = marker.getTitle();
        PointDeviceBean pointDeviceBean = daoSession.getPointDeviceBeanDao().queryBuilder().where(PointDeviceBeanDao.Properties.PointUuid.eq(uuid)).unique();
        if (UserInfo.getInstance().role.contains("设计")) {
            AlertDialog designDailog = new AlertListDialog.ListBuilder(this)
                    .setTitle("请操作")
                    .setIcon(R.drawable.ic_info)
                    .setItems(new String[]{"查看设备信息"}, ((dialog, which) -> {
                        dialog.dismiss();
                        String title = marker.getTitle();
                        if (pointDeviceBean.getPointType() == 6){
                            showCrossDialog(pointDeviceBean).show();
                        }
                        else {
                            Intent intent = new Intent(DesignMapActivity.this, PointDeviceActivity.class);
                            intent.putExtra("uuid", title);
                            startActivity(intent);
                        }
                    })).setNegativeButton("取消", (dialog, which) -> dialog.dismiss()).create();
            return designDailog;


        }
         if (pointDeviceBean == null) {
            ToastUtils.toast(this, "查询不到此设备....");
            return null;
        }
        if (pointDeviceBean.getPointType() == 6)
        {
            return   new AlertListDialog.ListBuilder(this)
                    .setDividerHeightRes(R.dimen.dp1)
                    .setDividerColorRes(R.color.color_divider)
                    .setTitle("请操作")
                    .setIcon(R.drawable.ic_info)
                    .setItems(new String[]{"查看信息", "删除"}, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0)
                            {
                                showCrossDialog(pointDeviceBean).show();
                            }
                            else if(which == 1){
                                Overlay overlay = deviceMap.get(pointDeviceBean.getPointUuid());
                                overlay.remove();
                                deletePointBean(pointDeviceBean);
                            }
                        }
                    }).setNegativeButton("取消",null)
                    .create();
        }
        String name = pointDeviceBean.getPointName();
        //设备类型 1：杆塔 2： 搭火点  3： 变压器 4 ：用户点 5 ：门铁 6：交叉跨越
        name += Utils.getDeviceType(pointDeviceBean.getPointType());
        final String finan_name = name;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(name);
        builder.setIcon(R.drawable.ic_info);
        View view = View.inflate(this, R.layout.maker_dialog, null);
        builder.setView(view);
        AlertDialog dialog = builder.create();
        Button btnDelDevice = view.findViewById(R.id.maker_dialog_del_dev);
        btnDelDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                TextView textView = new TextView(DesignMapActivity.this);
                textView.setText(finan_name);
                textView.setTextSize(20);
                textView.setTextColor(Color.BLACK);
                textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                textView.setPadding(0, 20, 0, 10);
                new AlertDialog.Builder(DesignMapActivity.this)
                        .setTitle("请确认是否删除")
                        .setIcon(R.drawable.ic_info)
                        .setView(textView)
                        .setNegativeButton("取消", (dialog, which) -> {
                            dialog.dismiss();
                        })
                        .setPositiveButton("确认删除", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Log.e(DesignMapActivity.class.getName(), "删除Maker");
                                Overlay overlay = deviceMap.get(marker.getTitle());
                                Log.e("point", deviceNameMap.get(marker.getTitle()));
                                deletePoint(overlay);
                            }
                        }).create().show();
            }
        });
        Button btnBranch = view.findViewById(R.id.maker_dialog_branch);
        btnBranch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                TextView textView = new TextView(DesignMapActivity.this);
                textView.setText(finan_name);
                textView.setTextSize(20);
                textView.setTextColor(Color.BLACK);
                textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                textView.setPadding(0, 20, 0, 10);
                new AlertDialog.Builder(DesignMapActivity.this)
                        .setTitle("请确认是否修改此设备")
                        .setIcon(R.drawable.ic_info)
                        .setView(textView)
                        .setNegativeButton("取消", (dialog, which) -> {
                            dialog.dismiss();
                        })
                        .setPositiveButton("确认修改", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Log.e(DesignMapActivity.class.getName(), "修改marker");
                                initListView(marker, pointDeviceBean);
                            }
                        }).create().show();
            }
        });
        Button btnCheckInfo = view.findViewById(R.id.maker_dialog_check_info);
        btnCheckInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("marker", marker.getTitle());
                dialog.dismiss();
                String title = marker.getTitle();
                Intent intent = new Intent(DesignMapActivity.this, PointDeviceActivity.class);
                intent.putExtra("uuid", title);
                startActivity(intent);
            }
        });
        Button btnCancel = view.findViewById(R.id.maker_dialog_cancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        return dialog;
    }

    //进行调整前桩信息
    private void initListView(final Marker marker, final PointDeviceBean point) {
        String[] from = {"name", "uuid", "img"};
        int[] to = {R.id.marker_lv_dialog_item_name, R.id.marker_lv_dialog_item_uuid, R.id.marker_lv_dialog_item_iv};
        pointDeviceBeanLongRxDao.getDao()
                .queryBuilder()
                .where(PointDeviceBeanDao.Properties.ProjectId.eq(point.getProjectId()))
                .orderDesc(PointDeviceBeanDao.Properties.PointId)
                .rx()
                .list()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(pointDeviceBeans -> {
                    View view_lv = View.inflate(DesignMapActivity.this, R.layout.marker_listview_dialog, null);
                    ListView listView = view_lv.findViewById(R.id.marker_lv_dialog);
                    TextView textView = new TextView(DesignMapActivity.this);
                    textView.setText("请选择前桩点");
                    textView.setTextSize(20);
                    textView.setTextColor(Color.WHITE);
                    textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                    textView.setPadding(0, 20, 0, 10);
                    textView.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
                    RelativeLayout.LayoutParams layoutParams =
                            new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
                    layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
                    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
                    textView.setLayoutParams(layoutParams);
                    listView.addHeaderView(textView, null, false);
                    List<Map<String, Object>> list = new ArrayList<>();
                    for (int i = 0; i < pointDeviceBeans.size(); i++) {
                        PointDeviceBean pointDeviceBean = pointDeviceBeans.get(i);
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("name", pointDeviceBean.getPointName());
                        map.put("uuid", pointDeviceBean.getPointUuid());
                        map.put("img", getResourceId(pointDeviceBean.getPointType()));
                        list.add(map);
                    }

                    SimpleAdapter simpleAdapter = new SimpleAdapter(DesignMapActivity.this,
                            list, R.layout.marker_listview_dialog_item, from, to);
                    listView.setAdapter(simpleAdapter);
                    AlertDialog lv_dialog = new AlertDialog
                            .Builder(DesignMapActivity.this)
                            .setView(view_lv)
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .create();
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            lv_dialog.dismiss();
                            PointDeviceBean prePointDeviceBean = pointDeviceBeans.get(position - 1);
                            String uuid = marker.getTitle();
                            PointDeviceBean currentPointDeviceBean = daoSession.getPointDeviceBeanDao().queryBuilder().where(PointDeviceBeanDao.Properties.PointUuid.eq(uuid)).unique();
                            List<PolylineDeviceBean> polylineDeviceBeans = daoSession.getPolylineDeviceBeanDao()
                                    .queryBuilder()
                                    .where(PolylineDeviceBeanDao.Properties.EndPointUUID.eq(currentPointDeviceBean.getPointUuid())).list();
                            if (polylineDeviceBeans.size() > 1) {
                                Toast.makeText(DesignMapActivity.this, "有多条线将当前设备作为终点，无法进行线路调整", Toast.LENGTH_LONG).show();
                            } else if (polylineDeviceBeans.size() == 1) {
                                PolylineDeviceBean polylineDeviceBean = polylineDeviceBeans.get(0);
                                updateBranchPolyline(prePointDeviceBean, currentPointDeviceBean, polylineDeviceBean);
                            }
                        }
                    });
                    lv_dialog.show();
                });

    }

    //图上和数据库更新线信息
    private void updateBranchPolyline(PointDeviceBean startPointDevice, PointDeviceBean endPointDeviceBean, PolylineDeviceBean polylineDeviceBean) {
        if (startPointDevice != null && endPointDeviceBean != null && polylineDeviceBean != null) {
            polylineDeviceBean.setStartPointUUID(startPointDevice.getPointUuid());
            polylineDeviceBean.setStartLatitude(startPointDevice.getLatitude());
            polylineDeviceBean.setStartLongitude(startPointDevice.getLongitude());
            polylineDeviceBean.setStartPointName(startPointDevice.getPointName());

            polylineDeviceBean.setEndPointUUID(endPointDeviceBean.getPointUuid());
            polylineDeviceBean.setEndLatitude(endPointDeviceBean.getLatitude());
            polylineDeviceBean.setEndLongitude(endPointDeviceBean.getLongitude());
            polylineDeviceBean.setEndPointName(endPointDeviceBean.getPointName());

            //更新当前点的前桩位信息
            endPointDeviceBean.setPrePointUUID(startPointDevice.getPointUuid());
            pointDeviceBeanLongRxDao.update(endPointDeviceBean);
            //更新连线
            polylineDeviceBeanLongRxDao
                    .save(polylineDeviceBean)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<PolylineDeviceBean>() {
                        @Override
                        public void call(PolylineDeviceBean polylineDeviceBean) {
                            String uuid = polylineDeviceBean.getPolylineUuid();
                            if (!uuid.isEmpty()) {
                                Overlay overlay = deviceMap.get(uuid);
                                if (overlay != null) {
                                    overlay.remove();
                                }
                                Bundle bundle = new Bundle();
                                bundle.putString("uuid", uuid);
                                List<LatLng> points = new ArrayList<>();
                                points.add(new LatLng(polylineDeviceBean.getStartLatitude(), polylineDeviceBean.getStartLongitude()));
                                points.add(new LatLng(polylineDeviceBean.getEndLatitude(), polylineDeviceBean.getEndLongitude()));
                                OverlayOptions mOverLayerOptions = new PolylineOptions().width(5).color(Color.RED).extraInfo(bundle).points(points);
                                Overlay newOverlay = mBaiduMap.addOverlay(mOverLayerOptions);
                                deviceMap.remove(uuid);
                                deviceMap.put(uuid, newOverlay);
                            }
                        }
                    });

        }
    }

    //选择设备类型
    private void showDeviceModelDialog(int type) //设备 1 pole, 2 wire, 3 transformer
    {
        String schemeName = projectBean.getSchemeName();
        String schemeType = projectBean.getSchemaType();
        String poleString = "";
        if (schemeName != null && !schemeName.isEmpty() && schemeType != null && !schemeType.isEmpty()) {
            switch (schemeType) {
                case "low":
                    List<MyLowVoltageSchemeBean> myLowVoltageSchemeBeans = daoSession.getMyLowVoltageSchemeBeanDao().queryBuilder()
                            .where(MyLowVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                    MyLowVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName())).list();
                    if (myLowVoltageSchemeBeans == null || myLowVoltageSchemeBeans.size() == 0) {
                        ToastUtils.toast(DesignMapActivity.this, "方案数据下载失败，请先在方案中打开打开确认");
                        return;
                    }
                    else {
                        MyLowVoltageSchemeBean myLowVoltageSchemeBean = myLowVoltageSchemeBeans.get(0);
                        poleString = myLowVoltageSchemeBean.getTypicalDesignModel();
                        transformerModel = myLowVoltageSchemeBean.getTransformerModel();
                        wireModel = myLowVoltageSchemeBean.getWireModel220V();
                        if (wireModel == null || wireModel.isEmpty()) {
                            wireModel = myLowVoltageSchemeBean.getWireModel380V();
                        }
                    }

                    break;
                case "high":
                    List<MyHighVoltageSchemeBean> myHighVoltageSchemeBeans = daoSession
                            .getMyHighVoltageSchemeBeanDao()
                            .queryBuilder().where(MyHighVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                    MyHighVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName()))
                            .list();
                    if (myHighVoltageSchemeBeans == null && myHighVoltageSchemeBeans.size() == 0) {
                        ToastUtils.toast(DesignMapActivity.this, "方案数据下载失败，请先在方案中打开打开确认");
                        return;
                    }
                    else {
                        MyHighVoltageSchemeBean myHighVoltageSchemeBean = myHighVoltageSchemeBeans.get(0);
                        poleString = myHighVoltageSchemeBean.getTypicalDesignModel();
                        transformerModel = myHighVoltageSchemeBean.getTransformerModel();
                        wireModel = myHighVoltageSchemeBean.getWireModel();
                    }
                    break;
            }
        }
        if (type == 1) {
            String[] poles = poleString.split("&");
            new AlertListDialog.ListBuilder(this)
                    .setDividerHeightRes(R.dimen.dp1)
                    .setDividerColorRes(R.color.color_divider)
                    .setTitle("请选择杆塔")
                    .setIcon(R.drawable.ic_info)
                    .setCancelable(false)
                    .setItems(poles, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            poleModel = poles[which];
                        }
                    }).create().show();
        }
    }

    //交叉跨越的对话框
    private AlertDialog showCrossDialog(PointDeviceBean pointDeviceBean){
        CrossDeviceBean crossDeviceBeanOld = daoSession.getCrossDeviceBeanDao().queryBuilder()
                .where(CrossDeviceBeanDao.Properties.CrossUUID.eq(pointDeviceBean.getPointUuid())).unique();
        int index = -1;
        if (crossDeviceBeanOld !=null)
        {
            index = crossDeviceBeanOld.getCode();
        }
        final int item = index;
           return     new AlertListDialog.ListBuilder(DesignMapActivity.this)
                        .setDividerHeightRes(R.dimen.dp1)
                        .setDividerColorRes(R.color.color_divider)
                        .setTitle("设置交叉跨越次数")
                        .setIcon(R.drawable.ic_info)
                        .setCancelable(false)
                        .setSingleChoiceItems(crossInfo, item, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Log.e("index",which+"");
                                CrossDeviceBean crossDeviceBean = new CrossDeviceBean();
                                crossDeviceBean.setProjectId(pointDeviceBean.getProjectId());
                                crossDeviceBean.setCrossUUID(pointDeviceBean.getPointUuid());
                                crossDeviceBean.setContent(crossInfo[which]);
                                crossDeviceBean.setCode(which);
                                if (crossDeviceBeanOld != null)
                                {
                                    daoSession.getCrossDeviceBeanDao().delete(crossDeviceBeanOld);
                                }
                                daoSession.getCrossDeviceBeanDao().insertOrReplace(crossDeviceBean);
                                dialog.dismiss();
                            }
                        }).create();

    }

    private boolean updatePosition(String UUID, LatLng latLng){
        PointDeviceBean pointDeviceBean = daoSession.getPointDeviceBeanDao().queryBuilder().where(PointDeviceBeanDao.Properties.PointUuid.eq(UUID)).unique();
        if (pointDeviceBean.getPointType() == 6)
        {
            pointDeviceBean.setLatitude(latLng.latitude);
            pointDeviceBean.setLongitude(latLng.longitude);
            daoSession.getPointDeviceBeanDao().update(pointDeviceBean);
            return  true;
        }
        else{
            return false;
        }
    }



    private void deletePointBean(PointDeviceBean pointDeviceBean) {
        pointDeviceBeanLongRxDao.getDao().delete(pointDeviceBean);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
        setOnSystemUiListener();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        mMapView = null;
        // 关闭前台定位服务
        mClient.disableLocInForeground(true);
        // 取消之前注册的 BDAbstractLocationListener 定位监听函数
        mClient.unRegisterLocationListener(myLocationListener);
        // 停止定位sdk
        mClient.stop();
    }
}